import {
  login,
  logout,
  getInfo,
  selectUserDep,
  checkUserState
} from '@/api/login'
import { getEnterprise } from '@/api//system/enterprise'
import {
  getToken,
  setToken,
  removeToken,
  removeUserState,
  setUserState,
  setEnterprisesList,
  getEnterprisesList,
  removeEnterprisesList,
  getEnterprises,
  setEnterprises,
  removeEnterprises
} from '@/utils/auth'
import { getXTenantId, setXTenantId, removeXTenantId } from '@/utils/rent'

const user = {
  state: {
    token: getToken(),
    id: '',
    name: '',
    nickName: '',
    avatar: '',
    roles: [],
    permissions: [],
    XTenantId: getXTenantId(),
    enterprisesList: getEnterprisesList() ? getEnterprisesList() : [],
    enterprises: getEnterprises() ? getEnterprises() : {},
    userState: undefined
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_NICK_NAME: (state, nickName) => {
      state.nickName = nickName
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_XTENANTID: (state, id) => {
      state.XTenantId = id
    },
    SET_USER_STATE: (state, userState) => {
      state.userState = userState
    },
    SET_ENTERPRISES_LIST: (state, enterprisesList) => {
      state.enterprisesList = enterprisesList
    },
    SET_ENTERPRISES: (state, enterprises) => {
      state.enterprises = enterprises
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const tenantId = userInfo.tenantId
      const phonenumber = userInfo.phonenumber.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      const platform = userInfo.platform
      return new Promise((resolve, reject) => {
        login(phonenumber, password, code, uuid, platform, tenantId)
          .then((res) => {
            setToken(res.token)
            commit('SET_TOKEN', res.token)
            setXTenantId(res['X-TenantId'])
            commit('SET_XTENANTID', res['X-TenantId'])
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.user
            // const avatar =
            //   user.avatar == '' || user.avatar == null
            //     ? require('@/assets/images/profile.jpg')
            //     : process.env.VUE_APP_BASE_API + user.avatar
            const avatar =
              user.avatar == '' || user.avatar == null
                ? require('@/assets/images/profile.jpg')
                : user.avatar
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', res.roles)
              commit('SET_PERMISSIONS', res.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
              //
              commit('SET_PERMISSIONS', res.permissions)
              //
            }
            commit('SET_ID', user.userId)
            commit('SET_NAME', user.userName)
            commit('SET_NICK_NAME', user.nickName)
            commit('SET_AVATAR', avatar)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            commit('SET_PERMISSIONS', [])
            removeToken()
            commit('SET_XTENANTID', '')
            removeXTenantId()
            commit('SET_USER_STATE', '')
            removeUserState()
            commit('SET_ENTERPRISES_LIST', [])
            removeEnterprisesList()
            commit('SET_ENTERPRISES', {})
            removeEnterprises()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        commit('SET_XTENANTID', '')
        removeXTenantId()
        commit('SET_ENTERPRISES_LIST', [])
        removeEnterprisesList()
        resolve()
      })
    },

    //登录前选择机构
    selectUserDepBeforeLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        selectUserDep(
          userInfo.phonenumber,
          userInfo.password,
          userInfo.uuid,
          userInfo.code
        )
          .then((response) => {
            if (response.code == 200) {
              commit('SET_USER_STATE', response.state)
              commit('SET_ENTERPRISES_LIST', response.depList)
              setEnterprisesList(response.depList)
              resolve(response)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    },

    //检查用户状态
    handleCheckUserStatus({ commit }) {
      return new Promise((resolve, reject) => {
        checkUserState().then((response) => {
          resolve(response)
        })
      })
    },

    //获取机构信息
    getEnterpriseInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getEnterprise().then((response) => {
          if(response.code == 200 && response.data){
            commit('SET_ENTERPRISES', response.data)
            setEnterprises(response.data)
            resolve(response)
          }else{
            reject(response)
          }

        })
      })
    },
    // 设置当前机构
    setCurrentEnterprise({ commit }, data){
      return new Promise((resolve, reject) => {
        // 存储当前机构
        commit('SET_ENTERPRISES', data)
        setEnterprises(data)
        commit('SET_XTENANTID', data.tenantId)
        setXTenantId(data.tenantId)
        resolve()
      })
    },
  }
}

export default user
